from sqlalchemy.orm import Session
from typing import Optional, List
from app.models.iaro_career.ite_dashboard_manual import ITEDashboardManual
from app.schema.dashboard_schema import DashboardCreate, DashboardUpdate

def get_dashboard_by_ite_id(db: Session, ite_id: int) -> Optional[ITEDashboardManual]:
    return db.query(ITEDashboardManual).filter(ITEDashboardManual.ite_id == ite_id).first()

def get_dashboards(db: Session, skip: int = 0, limit: int = 100) -> List[ITEDashboardManual]:
    return db.query(ITEDashboardManual).offset(skip).limit(limit).all()

def create_or_update_dashboard(db: Session, data: DashboardCreate) -> ITEDashboardManual:
    dashboard = get_dashboard_by_ite_id(db, data.ite_id)
    if dashboard:
        for key, value in data.dict(exclude_unset=True).items():
            setattr(dashboard, key, value)
    else:
        dashboard = ITEDashboardManual(**data.dict())
        db.add(dashboard)
    db.commit()
    db.refresh(dashboard)
    return dashboard